<?php

namespace Solle\PcbMessage\Http\Controllers;

use App\Models\AfterSales;
use App\Models\PayOrder;
use GrahamCampbell\ResultType\Success;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use PcbMessage;
use Solle\PcbMessage\MessagePushRecord;
use Utils\response\Fail;
use Illuminate\Support\Facades\Redis;
use Utils\SystemVisitor;

class Message extends Controller
{
    public function chat(Request $request){
        $input      = $request->input();
        $session    = $input["session"]??"";
        $key        = $input["key"]??"";
        if(empty($session) || empty($key)){
            return view("");
        }
        $info       = PcbMessage::parseFeedbackKey($key);
        if(empty($info)){
            return view("");
        }
        if($info["object_type"] === PcbMessage::MESSAGE_OBJECT_TYPE_PAY_ORDER){
            $object = PayOrder::where("id",$info["object_id"])->first();
            if(empty($object)){
                return view("");
            }
            $title  = $object->order_no;
            $icon   = "/resources/images/chat.png";
        }elseif ($info["object_type"] === PcbMessage::MESSAGE_OBJECT_TYPE_AFTER_SALES){
            $log = AfterSales::where("id",$info["object_id"])->first();
            if(empty($log)){
                return view("");
            }
            $title  = $log->serial_no;
            $icon   = "/resources/images/chat.png";
        }else{
            $object = DB::table("pcb_order")->where("id",$info["object_id"])->first();
            if(empty($object)){
                return view("");
            }
            $title = $object->title;
            if($object->type == "fpc_pcb"){
                $icon   = "/resources/images/fpc.png";
            }else{
                if($object->type == "assembly"){
                    $icon   = "/resources/images/assembly.png";
                } else if($object->type == "SMD"){
                    $icon   = "/resources/images/smd.png";
                }else{
                    $icon = "/resources/images/pcb.png";
                }
            }
        }
        return view("pcbmessage::chat",["title" => $title,"icon" => $icon]);
    }

    public function sendMessage(Request $request)
    {
        $params = $request->post();
        try {
            $id = PcbMessage::sendMessage(
                \Solle\PcbMessage\PcbMessage::MESSAGE_TYPE_FEEDBACK
                ,$request->feedback_object
                ,$params
            );
            $message = \Solle\PcbMessage\Message::newById($id,$request->feedback_object["current"]);
            return $this->responseSuccess($message);
        }catch (\Throwable $e){
            return $this->responseFail($e->getMessage());
        }
    }

    public function sendImage(Request $request){
        $image = $request->file("file");
        if(!$image->isValid()){
            return $this->responseFail("Invalid file");
        }
        try {
            $session    = $request->post("session");
            $filename   = $image->getClientOriginalName();
            $path       = DIRECTORY_SEPARATOR . $image->store("uploads/" . date("Ymd") . DIRECTORY_SEPARATOR);
            $content    = array(
                "type"      => "image",
                "image"     => array(
                    "src"       => $path,
                    "filename"  => $filename,
                ),
                "session"   => $session
            );
            $id = PcbMessage::sendMessage(
                \Solle\PcbMessage\PcbMessage::MESSAGE_TYPE_FEEDBACK
                ,$request->feedback_object
                ,$content
            );
            $message = \Solle\PcbMessage\Message::newById($id,SystemVisitor::getId());
            return $this->responseSuccess($message);
        }catch (\Throwable $e){
            return $this->responseFail($e->getMessage());
        }
    }

    public function sendFile(Request $request){
        $file = $request->file("file");
        if(!$file->isValid()){
            return $this->responseFail("Invalid file");
        }
        try {
            $session    = $request->post("session");
            $file_size  = $file->getSize();
            $filename   = $file->getClientOriginalName();
            $path       = DIRECTORY_SEPARATOR . $file->store("uploads/" . date("Ymd") . DIRECTORY_SEPARATOR);
            $content    = array(
                "type"      => "file",
                "file"      => array(
                    "src"       => $path,
                    "filename"  => $filename,
                    "file_size" => $file_size,
                ),
                "session"   => $session
            );
            $id = PcbMessage::sendMessage(
                \Solle\PcbMessage\PcbMessage::MESSAGE_TYPE_FEEDBACK
                ,$request->feedback_object
                ,$content
            );
            $message = \Solle\PcbMessage\Message::newById($id,SystemVisitor::getId());
            return $this->responseSuccess($message);
        }catch (\Throwable $e){
            return $this->responseFail($e->getMessage());
        }
    }

    public function getMessages($session,Request $request){
        $list = DB::table("pcb_message")->where("session","=",$session)->orderBy("create_time","asc")->get();
        $list = \Solle\PcbMessage\Message::newList($list,$request->feedback_object["current"]??"",$session);
        return $this->responseSuccess($list);
    }

    public function sseMessages(Request $request){
        $input      = $request->input();
        header("Content-Type: text/event-stream");
        header("Cache-Control: no-cache");
        header("Connection:keep-alive");

        $session    = $input["session"]??"";
        $key        = $input["key"]??"";
        if(empty($session) || empty($key)){
            echo "data:" + json_encode([]) + "\n\n";exit;
        }
        $info       = PcbMessage::parseFeedbackKey($key);
        if(empty($info)){
            echo "data:" + json_encode([]) + "\n\n";exit;
        }
        list($max_id,$max_timestamp) = MessagePushRecord::getRecord($session,SystemVisitor::getRole(),SystemVisitor::getId());
        $handle        = DB::table("pcb_message")->where("session","=",$session);
        if(!empty($max_timestamp) && !empty($max_id)){
            $handle->where("create_time",">",$max_timestamp)
                ->where("id",">",$max_id);
        }
        $list = $handle->orderBy("create_time","asc")->get();
        $list = \Solle\PcbMessage\Message::newList($list,SystemVisitor::getId(),$session);

        echo "data:" . json_encode($list) . "\n\n";

        exit;
    }


}
